let store  = require('store')


let token  = null;
let roleNameSet  = new Set();

export function setToken(tkn){
  token  = tkn;
}


export function getToken(){
  return token;
}


export function addRole(roleName){
  roleNameSet.add(roleName);
}


export function deleteRole(roleName){
  roleNameSet.delete(roleName);
}


export function hasRole(roleName){
  return roleNameSet.has(roleName);
}


export function clear(){
  token  = null;
  console.log(roleNameSet);
  roleNameSet.clear();
}


export function loadAuthData(){
  // Load token
  const tkn  = store.get('token');

  if(tkn  &&  tkn.length > 0){
    token  = tkn;
  }
  else{
    token  = null;
  }

  // Load roles name
  const roleNameArray  = store.get('roles');
  if(roleNameArray){
    for(name of roleNameArray){
      roleNameSet.add(name);
    }
  }
}


export function storeAuthData(){
  store.clearAll();

  if(token){
    store.set('token', token);

    if(roleNameSet.size > 0){
      const roleNamesArray  = Array.from(roleNameSet);
      console.log("Store", roleNamesArray, 'as roles');
      store.set('roles', roleNamesArray);
    }
  }
}
